#! /bin/bash
### BEGIN INIT INFO
# Provides:          iptables-init
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Easy initialization iptables rules
# Description:       Shell script to easily initialize iptables rules by incorporating recurrent security 
### END INIT INFO

# Author: Boris Klymko <boris.klymko@gmail.com>

PATH=/sbin:/bin:/usr/bin
DESC='initialization iptables rules'
NAME="$(basename "$0")"
DIR_BIN="$(cd "$(dirname "$0")" && pwd)"
DIR_LIB="$DIR_BIN"
SCRIPTNAME="$DIR_BIN/$NAME"

# Exit is not runned by root
[ $(id -u) -eq 0 ] || exit 1

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

# Options
. "$DIR_BIN"/iptables-config

# Functions
. "$DIR_BIN"/iptables-lib

# Kernel parameters (sysctl)
"$DIR_BIN"/iptables-commands

#
# Function that starts the daemon/service
#
do_start() {
  . "$DIR_BIN"/iptables_perso
  for table in filter mangle nat raw; do
    . "$DIR_BIN"/iptables_${table}
    enableTable_${table}
  done
}

#
# Function that stops the daemon/service
#
do_stop() {
  for table in filter mangle nat raw; do
    . "$DIR_BIN"/iptables_${table}
    disableTable_${table}
  done
}

case "$1" in
  start)
    [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
    do_start
    [ "$VERBOSE" != no ] && log_end_msg 0
    ;;
  stop)
    [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
    do_stop
    [ "$VERBOSE" != no ] && log_end_msg 0
    ;;
  status)
    iptables -nL | grep -q TCP_INPUT && {
      log_success_msg "$NAME is running"
      exit 0
    }
    log_failure_msg "$NAME is not running"
    exit 1
    ;;
  restart|force-reload)
    log_daemon_msg "Restarting $DESC" "$NAME"
    do_start
    log_end_msg 0
    ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
    exit 3
    ;;
esac

:
